package com.wing.ext.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wing.common.Constants;
import com.wing.common.util.FileUtils;
import com.wing.common.util.GUID;
import com.wing.common.util.RequestUtils;
import com.wing.common.util.ScaleImage;

@Controller
@RequestMapping(value = "/res")
public class ResController {
  
	@RequestMapping(value = "get/{url}")
	public String get(@PathVariable String url) {
		return "/pub/selectImage/"+url;
	}
	
	@RequestMapping(value = "upload")
	public @ResponseBody String upload(@RequestParam MultipartFile imgFile  ,
			HttpServletRequest request,
			HttpServletResponse response
		    ) throws Exception {
		response.setContentType("text/html; charset=UTF-8");
		String sitePath = RequestUtils.getSitePath(request);
		String c = request.getParameter("c");
		String type = request.getParameter("type");
		String savePath=request.getSession().getServletContext().getRealPath("/")+"site/"+sitePath+"/document/siteimg/"+c;
		String urlPath=request.getContextPath()+"/site/"+sitePath+"/document/siteimg/"+c;
		String filename = imgFile.getOriginalFilename();
        // 获取文件扩展名:
        String ext = "";
        int pos;
        if((pos = filename.lastIndexOf('.'))!=(-1)) {
            ext = filename.substring(pos).trim();
        }
        String uuid =  new GUID().toString();
        String newFileName="";
        
        if("p".equals(type)){
        	//如果type==‘p’ 说明是产品上传，要生成缩略图
        	newFileName="p_"+uuid+ext;
        	if (!imgFile.isEmpty()) {
    			FileUtils.saveFile(savePath+newFileName, imgFile.getBytes());
    		}
        	String smallFileName="p_small_"+uuid+ext;
        	ScaleImage is = new ScaleImage();   
            try {   
                is.saveImageAsJpg(savePath+newFileName, savePath+smallFileName,200);   
            } catch (Exception e) {   
                e.printStackTrace();   
            }
        }else{
        	newFileName=uuid+ext;
        	if (!imgFile.isEmpty()) {
    			FileUtils.saveFile(savePath+newFileName, imgFile.getBytes());
    		}
        }		
		
		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("url", urlPath + newFileName);
		response.getWriter().print(obj.toJSONString());
		return null;

	}
	@RequestMapping(value = "newpath")
	public @ResponseBody String newpath(String path ,
			HttpServletRequest request,
			HttpServletResponse response
		    ) throws Exception {
		String c=request.getParameter("c");
		path = path.toLowerCase();
		String sitePath = RequestUtils.getSitePath(request);
		String savePath=request.getSession().getServletContext().getRealPath("/")+"site/"+sitePath+"/document/siteimg/"+c;
		new File(savePath+path+"/").mkdirs();
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	@RequestMapping(value = "show")
	public @ResponseBody String show(
			HttpServletRequest request,
			HttpServletResponse response,String path
		    ) throws Exception {
		String sitePath = RequestUtils.getSitePath(request);
		String type = request.getParameter("type");
		//根目录路径，可以指定绝对路径，比如 /var/www/attached/
		String rootPath = request.getSession().getServletContext().getRealPath("/")+"site/"+sitePath+"/document/siteimg/";
		//根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
		String rootUrl  = request.getContextPath()+"/site/"+sitePath+"/document/siteimg/";
		//图片扩展名
		String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

		//根据path参数，设置各路径和URL
		path = path==null?"":path;
		int pos=path.lastIndexOf(",");
		if(pos != -1){
			path=path.substring(0,pos);
		}
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0, currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}

		//排序形式，name or size or type
		String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

		//不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			return getError("Access is not allowed.");
		}
		//最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			return getError("Parameter is not valid."); 
		}
		//目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if(!currentPathFile.isDirectory()){
			return getError("Directory does not exist."); 
		}

		//遍历目录取的文件信息
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		if(currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if(file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if(file.isFile()){
					if("p".equals(type)){
						//如果是产品展示，则只显示小图
						if(fileName.indexOf("p_small_")==-1){
							continue;
						}
					}else{
						//如果不是产品展示，则不显示任何产品类图片
						if(fileName.indexOf("p_")!=-1){
							continue;
						}
					}
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				fileList.add(hash);
			}
		}

		if ("size".equals(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
		}
		JSONObject result = new JSONObject();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);

//		response.setContentType("application/json; charset=UTF-8");
		return result.toJSONString();

	}

	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}

	public class NameComparator implements Comparator {
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable)a;
			Hashtable hashB = (Hashtable)b;
			if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String)hashA.get("filename")).compareTo((String)hashB.get("filename"));
			}
		}
	}
	public class SizeComparator implements Comparator {
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable)a;
			Hashtable hashB = (Hashtable)b;
			if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
				return 1;
			} else {
				if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) {
					return 1;
				} else if (((Long)hashA.get("filesize")) < ((Long)hashB.get("filesize"))) {
					return -1;
				} else {
					return 0;
				}
			}
		}
	}
	public class TypeComparator implements Comparator {
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable)a;
			Hashtable hashB = (Hashtable)b;
			if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype"));
			}
		}
	}
}

